var express = require('express');
var router = express.Router();
var {newsModel, noticeModel, departModel} = require("../module/user")
var {messageModel} = require('../module/message')
var {Types: {ObjectId}} = require('mongoose')

router.get('/new', async function (req, res, next) {
    let newslist = await newsModel.find({})
    res.send({newslist})
});

router.get('/notice', async (req, res) => {
    let data = await noticeModel.find()
    data = data.map(item => ({...item._doc}))
    let lv1 = data.filter(item => item.parent === 1)
    let lv2 = data.filter(item => item.parent === 2)
    let lv3 = data.filter(item => item.parent === 3)
    lv1.forEach(item1 => {
        item1.children = []
        item1.title = item1.noticeName
        item1.key = item1._id
        item1.label = item1.noticeName
        lv2.forEach(item2 => {
            item2.children = []
            item2.title = item2.noticeName
            item2.key = item2._id
            item2.label = item2.noticeName
            lv3.forEach(item3 => {
                item3.children = []
                item3.title = item3.noticeName
                item3.key = item3._id
                item3.label = item3.noticeName
                if (item3.notice_id.toString() == item2._id.toString()) {
                    item2.children.push(item3)
                }
            })
            if (item2.notice_id.toString() == item1._id.toString()) {
                item1.children.push(item2)
            }
        })
    })
    data = lv1
    res.send({noticedata: data})
})

router.get('/notice_four', async (req, res) => {
    let notice_id = req.query.notice_id
    let obj = {}
    if (notice_id && notice_id != '63e05c0d0e25230e1c481244') {
        obj.notice_id = ObjectId(notice_id)
        let datas = await noticeModel.aggregate([{
            $match: obj
        }])
        res.send({datas})
    } else if (notice_id == '63e05c0d0e25230e1c481244') {
        console.log(2)
        let data = await noticeModel.find()
        let datas = data.filter(item => item.parent === 4)
        res.send({datas})
    }
})
router.get('/noticetype', async (req, res) => {
    let noticetype = await noticeModel.find()
    let data = noticetype.filter(item => item.parent !== 4)
    res.send(data)
})

//消息接口
router.get('/message', async (req, res) => {
    let start = req.query.start
    let end = req.query.end
    let messageData = await messageModel.find({"remindtime": {$gte: start}, "remindtime": {$lte: end}})
    let total = messageData.length
    res.send({messageData, total})
})
router.put('/messageupt', async (req, res) => {
    let {id, status} = req.body
    await messageModel.updateOne({_id: id}, {status: status})
    res.send({'msg': "成功"})
})
module.exports = router